from peewee import *
from src.models.BaseModel import BaseModel
from src.util.Model2Dict import m2d
from src.entry.Entrys import Page


class File(BaseModel):
    id = BigIntegerField(primary_key=True)  # 文件编号
    parent = BigIntegerField()  # 父文件夹
    fType = CharField(db_column='f_type')  # 文件类型
    name = CharField()  # 文件名称
    path = CharField()  # 文件路径
    suffix = CharField()  # 文件后缀
    size = IntegerField()  # 文件大小
    hidden = CharField()  # 是否隐藏
    createBy = BigIntegerField(db_column='create_by')  # 创建人
    createTime = DateTimeField(db_column='create_time')  # 创建时间
    updateBy = BigIntegerField(db_column='update_by')  # 修改人
    updateTime = DateTimeField(db_column='update_time')  # 修改时间
    log = CharField()  # 开启访问日志记录
    extend = CharField()  # 是否继承父权限

    # 分页查询
    @staticmethod
    def getAll(page: Page = Page(), cdn: dict = None):
        if cdn is None:
            cdn = dict()
        query = File.select()
        if cdn.get("parent") is not None:
            query = query.where(File.parent == cdn.get('parent'))
        if cdn.get('fType'):
            query = query.where(File.fType == cdn.get('fType'))
        if cdn.get('hidden'):
            query = query.where(File.hidden == cdn.get('hidden'))
        if cdn.get('name'):
            query = query.where(File.name.contains(cdn.get('name')))
        if cdn.get('createTime'):
            t: list[str] = cdn.get('createTime')
            if t[0]:
                query = query.where(File.createTime > t[0])
            if t[1]:
                query = query.where(File.createTime < t[1])
        if cdn.get('order'):
            order: dict = cdn.get('order')
            if order.get('createTime') and order.get('createTime') == 'asc':
                query = query.order_by(File.createTime.asc())
            if order.get('createTime') and order.get('createTime') == 'desc':
                query = query.order_by(File.createTime.desc())
        r = query.paginate(page.num, page.size).dicts()
        page.count = query.count()
        page.rows = m2d(r)
        return page.__dict__

    # 添加文件数据
    @staticmethod
    def add(data: dict = None):
        if data is None:
            data = dict()
        return File.insert(data).execute()

    # 删除文件数据
    @staticmethod
    def delList(f_ids: list[int]):
        File.delete().where(File.id.in_(f_ids)).execute()
        return True

    # 根据id 获取数据
    @staticmethod
    def getOneById(fid: int) -> dict | None:
        file = File.select().where(File.id == fid)
        data = m2d(file.dicts())
        if len(data) > 0:
            return data[0]
        return None

    # 根据文件id集合 获取文件信息集合
    @staticmethod
    def getListInId(f_ids: list[int]) -> list[dict]:
        q = File.select().where(File.id.in_(f_ids))
        data = m2d(q.dicts())
        return data

    # 查询某文件夹下的所有文件
    @staticmethod
    def getListByParent(p: int) -> list[dict]:
        file = File.select().where(File.parent == p)
        data = m2d(file.dicts())
        return data

    # 根据路径查询文件信息
    @staticmethod
    def getByPath(path: str):
        path = path.replace('\\', '/')
        path_list = path.split('/')[1:]
        def _get():

            return


        # file = File.select().where(File.path == path)
        # data = m2d(file.dicts())
        # if len(data) > 0:
        #     return data[0]
        # return None

    # 更新文件数据
    @staticmethod
    def updateFile(f_id: int, data: dict):
        File.update(data).where(File.id == f_id).execute()
        return True

    class Meta:
        table_name = "sys_file"


class FileAuth(BaseModel):
    id = BigIntegerField(primary_key=True)  # 文件编号
    fid = BigIntegerField()
    authType = CharField(db_column='auth_type')
    canRead = CharField(db_column='can_read')
    canWrite = CharField(db_column='can_write')
    objId = BigIntegerField(db_column='obj_id')
    token = CharField()
    createTime = DateTimeField(db_column='create_time')  # 创建时间
    exceedTime = IntegerField(db_column='exceed_time')  # 过期时间 ms

    # 查询文件的所有权限
    @staticmethod
    def getAll(f_id: int, auth_type: str = ""):
        q = FileAuth.select()
        if auth_type:
            q = q.where(FileAuth.authType == auth_type)
        data = q.where(FileAuth.fid == f_id).dicts()
        return m2d(data)

    # 清除某文件的权限
    @staticmethod
    def clearAuthInFId(f_id: list[int], auth_type: str = ""):
        q = FileAuth.delete()
        if auth_type:
            q = q.where(FileAuth.authType == auth_type)
        q = q.where(FileAuth.fid.in_(f_id))
        q.execute()
        return True

    @staticmethod
    def getByObjId(o_id: int, a_type: str = '', f_id: int = 0):
        q = FileAuth.select()
        if f_id:
            q = q.where(FileAuth.fid == f_id)
        if a_type:
            q = q.where(FileAuth.authType == a_type)
        q = q.where(FileAuth.objId == o_id)
        return m2d(q.dicts())

    # 根据id删除权限
    @staticmethod
    def delAuthInAId(a_id: list[int]):
        q = FileAuth.delete()
        q = q.where(FileAuth.id.in_(a_id))
        q.execute()
        return True

    # 删除
    @staticmethod
    def delAuthInObjId(obj_ids: list[int], a_type: str = '', f_id: int = 0):
        q = FileAuth.delete()
        if f_id:
            q = q.where(FileAuth.fid == f_id)
        if a_type:
            q = q.where(FileAuth.authType == a_type)
        q = q.where(FileAuth.objId.in_(obj_ids))
        q.execute()
        return True

    # 添加权限
    @staticmethod
    def addAuth(data: dict):
        FileAuth.insert(data).execute()
        return True

    # 更新权限
    @staticmethod
    def updateAuth(data: dict):
        a_id = data.get("id")
        if not a_id:
            return False
        q = FileAuth.update(data).where(FileAuth.id == a_id)
        q.execute()
        return True

    @staticmethod
    def updateAuthByObjId(obj_ids: int, data: dict, a_type: str = '', f_id: int = 0):
        q = FileAuth.update(data)
        if f_id:
            q = q.where(FileAuth.fid == f_id)
        if a_type:
            q = q.where(FileAuth.authType == a_type)
        q = q.where(FileAuth.objId == obj_ids)
        q.execute()
        return True

    class Meta:
        table_name = "sys_file_auth"
